﻿using System;
using System.ServiceModel;
using System.ServiceModel.Channels;
using Bricks;
using Bricks.Injecting;

namespace Motar.ServiceModel
{
    
    /// <summary>
    /// 
    /// </summary>
    public class InjectingInstanceProvider : FacadeBase<IContainerFacade>, IInjectingInstanceProvider
    {

        public InjectingInstanceProvider(IContainerFacade containerFacade) :
            base(() => containerFacade)
        {
            if (containerFacade == null)
            {
                throw new ArgumentNullException("containerFacade");
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="instanceContext"></param>
        /// <returns></returns>
        public object GetInstance(InstanceContext instanceContext)
        {
            return GetInstance(instanceContext, null);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="instanceContext"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        public virtual object GetInstance(InstanceContext instanceContext, Message message)
        {
            return Execute<object>(containerFacade => containerFacade.Resolve(instanceContext.Host.Description.ServiceType));
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="instanceContext"></param>
        /// <param name="instance"></param>
        public virtual void ReleaseInstance(InstanceContext instanceContext, object instance)
        {
            Execute(containerFacade => containerFacade.Release(instance));
        }
    }
}
